import { Octree } from 'three/examples/jsm/math/Octree.js';
import * as THREE from 'three';

export default class CollisionSystem {
  constructor(scene) {
    this.octree = new Octree();
    this.scene = scene;
    this.collidableObjects = [];
  }

  /**
   * 添加模型到碰撞系统
   * @param {THREE.Object3D} model - 3D模型对象
   * @param {boolean} [addToScene=true] - 是否同时添加到场景
   */
  addModel(model, addToScene = true) {
    if (!model) return;
    
    // 添加到八叉树
    this.octree.fromGraphNode(model);
    this.collidableObjects.push(model);
    
    if (addToScene && this.scene) {
      this.scene.add(model);
    }
    
    console.log(`Model added to collision system: ${model.name || 'unnamed'}`);
  }

  /**
   * 从碰撞系统中移除模型
   * @param {THREE.Object3D} model - 要移除的3D模型
   * @param {boolean} [removeFromScene=true] - 是否同时从场景移除
   */
  removeModel(model, removeFromScene = true) {
    if (!model) return;
    
    const index = this.collidableObjects.indexOf(model);
    if (index !== -1) {
      this.collidableObjects.splice(index, 1);
      this.rebuildOctree();
      
      if (removeFromScene && this.scene) {
        this.scene.remove(model);
      }
      
      console.log(`Model removed from collision system: ${model.name || 'unnamed'}`);
    }
  }

  /**
   * 重建八叉树（当删除对象后需要调用）
   */
  rebuildOctree() {
    console.log('Rebuilding octree...');
    this.octree = new Octree();
    this.collidableObjects.forEach(model => {
      this.octree.fromGraphNode(model);
    });
  }

  /**
   * 检测球体碰撞
   * @param {THREE.Sphere} sphere - 检测球体
   * @returns {Array} 碰撞结果数组
   */
  checkSphereCollision(sphere) {
    return this.octree.sphereIntersect(sphere);
  }

  /**
   * 检测射线碰撞
   * @param {THREE.Ray} ray - 检测射线
   * @returns {Object|null} 碰撞结果
   */
  checkRayCollision(ray) {
    return this.octree.rayIntersect(ray);
  }

  /**
   * 检测胶囊体碰撞
   * @param {THREE.Capsule} capsule - 检测胶囊体
   * @returns {Array} 碰撞结果数组
   */
  checkCapsuleCollision(capsule) {
    return this.octree.capsuleIntersect(capsule);
  }

  /**
   * 检测玩家碰撞
   * @param {THREE.Vector3} position - 玩家位置
   * @param {number} [radius=0.5] - 碰撞半径
   * @param {number} [height=1.8] - 玩家高度
   * @returns {boolean} 是否发生碰撞
   */
  checkPlayerCollision(position, radius = 0.5, height = 1.8) {
    const capsule = new THREE.Capsule(
      new THREE.Vector3(position.x, position.y - height/2 + radius, position.z),
      new THREE.Vector3(position.x, position.y + height/2 - radius, position.z),
      radius
    );
    
    return this.checkCapsuleCollision(capsule).length > 0;
  }

  /**
   * 清除所有碰撞检测对象
   */
  clear() {
    console.log('Clearing collision system');
    this.octree = new Octree();
    this.collidableObjects = [];
  }
}